//
//  LoginViewController.m
//  TestApplication
//
//  Created by Hanlingyu on 16/8/29.
//  Copyright © 2016年 ltq. All rights reserved.
//

#import "LoginViewController.h"
#import "AFNetworking.h"
#import "MainViewController.h"
#import "TAMacro.h"
#import "SearchPersonContent.h"
@interface LoginViewController ()
<
    UITextFieldDelegate
>

@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (nonatomic, strong) NSString *phoneNumber;
@property (nonatomic, strong) NSString *password;
@property (nonatomic, strong) NSString *user_id;
//@property (nonatomic, strong) NSString *user;
@property (weak, nonatomic) IBOutlet UIButton *forgetButton;
@property (nonatomic, assign) BOOL canLogin;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
   
    
    self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    self.phoneNumberTextField.keyboardType = UIKeyboardTypePhonePad;
    self.passwordTextField.keyboardType = UIKeyboardTypeASCIICapable;
    self.phoneNumberTextField.delegate = self;
    self.passwordTextField.delegate = self;
    
    // 监听键盘的弹起和回收
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillAppear:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
    

    
    
}
- (void)popLastViewController:(UIBarButtonItem *)buttonItem {
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

// 点击登录后通过code判断是否允许登录
- (void)loginData {
    // c=User&m=loginWithPhone&p=%7B%22countryCode%22%3A%22%2B86%22%2C%22tel%22%3A%2213029269187%22%2C%22password%22%3A%22qwer1234%22%7D&t=t&v=v105
    // c=User&m=loginWithPhone&p=%7B%22countryCode%22%3A%22%2B86%22%2C%22tel%22%3A%2213029269187%22%2C%22password%22%3A%22qwer1234%22%7D&t=t&v=v105
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *postURLString = @"http://api.zheli.io:9501/";
    
//    self.phoneNumber = @"13029269187";
//    self.password = @"qwer1234";
    
    NSString *text = [NSString stringWithFormat:@"{\"countryCode\":\"+86\",\"tel\":\"%@\",\"password\":\"%@\"}", self.phoneNumber, self.password];
    NSString *utf8Text = [text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
    //    NSString *p = [self URLEncodedString:utf8Text];
    NSString *parmeters = [NSString stringWithFormat:@"c=User&m=loginWithPhone&p=%@&t=t&v=v105", utf8Text];
    // 确定 parameter 字符串中含有:/?#[]@!$&’()*+,;=这些字符时候，这些字符需要被转化，以免与语法冲突
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    // 设置请求参数的字符串, 自定义
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        
        return parmeters;
    }];
    // 正常post发送
    [manager POST:postURLString parameters:parmeters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        self.user_id = responseObject[@"content"][@"id"];
        [self getUserInfo];
//
//        NSInteger postCode = (NSInteger)responseObject[@"code"];
//        if (postCode == 200) {
//            [self getUserInfo];
//            NSLog(@"登录成功");
//            _canLogin = YES;
//        } else {
//            NSLog(@"登录失败");
//            NSLog(@"%ld", postCode);
//            _canLogin = NO;
//        }
        
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败: %@", error);
    }];
}

// 获取用户信息
- (void)getUserInfo {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *postURLString = @"http://api.zheli.io:9501/";
    
    //    self.phoneNumber = @"13029269187";
    //    self.password = @"qwer1234";
    
    // c=User&m=getUserInfo&p=%7B%22id%22%3A%2257c01d33a9a36d0621c123f7%22%7D&t=t&v=v105
    // c=User&m=getUserInfo&p=%7B%22id%22%3A%2257c01d33a9a36d0621c123f7%22%7D&t=t&v=v105
    
    
    NSString *text = [NSString stringWithFormat:@"{\"id\":\"%@\"}", self.user_id];
    NSString *utf8Text = [text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
    //    NSString *p = [self URLEncodedString:utf8Text];
    NSString *parmeters = [NSString stringWithFormat:@"c=User&m=getUserInfo&p=%@&t=t&v=v105", utf8Text];
    NSLog(@"%@", parmeters);
    
    // 确定 parameter 字符串中含有:/?#[]@!$&’()*+,;=这些字符时候，这些字符需要被转化，以免与语法冲突
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    // 设置请求参数的字符串, 自定义
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        
        return parmeters;
    }];
    // 正常post发送
    [manager POST:postURLString parameters:parmeters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject);
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        //登陆成功后把用户名和密码存储到UserDefault
        [userDefaults setObject:responseObject forKey:@"user"];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败: %@", error);
    }];
    
    
}


- (IBAction)loginAction:(id)sender {
    
    _phoneNumber = self.phoneNumberTextField.text;
    _password = self.passwordTextField.text;
    [self loginData];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    window.rootViewController = [[MainViewController alloc] init];
    
//    if (_canLogin == YES) {
//        
//    } else {
//        NSLog(@"请重新输入");
//    }
//    
    
}
- (IBAction)codeLoginAction:(id)sender {
}
- (IBAction)forgetPasswordAction:(id)sender {
}
- (IBAction)popLastViewControllerAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
    
}



- (void)keyboardWillHidden:(NSNotification *)notification {
    
    NSLog(@"键盘回收");
    [UIView animateWithDuration:0.5 animations:^{
        
        self.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        
    }];
    
}


- (void)keyboardWillAppear:(NSNotification *)notification {
    
    NSLog(@"键盘出现");
    // 找到键盘的尺寸
    CGRect rect = [[[notification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyBoardHeight = rect.size.height;
    CGFloat y = SCREEN_HEIGHT - CGRectGetMaxY(_forgetButton.frame);
    CGFloat contentSize_Y = keyBoardHeight - y;
    if (contentSize_Y > 0) {
        [UIView animateWithDuration:0.5 animations:^{
            
            self.view.frame = CGRectMake(0, - contentSize_Y, SCREEN_WIDTH, SCREEN_HEIGHT);
            
        }];
        
    }
}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.phoneNumberTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
